package io.rong.imkit.webview

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.net.Uri
import android.os.Message
import android.view.View
import android.webkit.*
import android.webkit.WebStorage.QuotaUpdater

class DefaultWebChromeClient : WebChromeClient() {
    private var listener: WebChromeClientListener? = null
    fun setListener(listener: WebChromeClientListener?) {
        this.listener = listener
    }

    @SuppressLint("NewApi")
    override fun onShowFileChooser(
        webView: WebView,
        filePathCallback: ValueCallback<Array<Uri>>,
        fileChooserParams: FileChooserParams
    ): Boolean {
        val acceptTypes = fileChooserParams.acceptTypes
        var acceptType = ""
        for (i in acceptTypes.indices) {
            if (acceptTypes[i] != null && acceptTypes[i]!!.isNotEmpty()) acceptType += acceptTypes[i]
                .toString() + ";"
        }
        if (acceptType.isEmpty()) acceptType = "*/*"
        val vc = ValueCallback<Uri?> { value ->
            val result: Array<Uri>? = value?.let { arrayOf(it) }
            filePathCallback.onReceiveValue(result)
        }
        openFileChooser(vc, acceptType, "filesystem")
        return true
    }

    // For Android < 3.0
    fun openFileChooser(uploadFile: ValueCallback<Uri?>?) {
        if (listener != null) {
            listener!!.openFileChooser(uploadFile, "", "")
        } else {
            openFileChooser(uploadFile, "", "")
        }
    }

    // For Android 3.0+
    fun openFileChooser(uploadFile: ValueCallback<Uri?>?, acceptType: String?) {
        if (listener != null) {
            listener!!.openFileChooser(uploadFile, acceptType, "")
        } else {
            openFileChooser(uploadFile, acceptType, "")
        }
    }

    // For Android > 4.1.1
    fun openFileChooser(
        uploadFile: ValueCallback<Uri?>?,
        acceptType: String?,
        capture: String?
    ) {
        listener?.openFileChooser(uploadFile, acceptType, capture)
    }

    override fun onProgressChanged(view: WebView, newProgress: Int) {
        listener?.onProgressChanged(view, newProgress)
    }

    override fun onReceivedTitle(view: WebView, title: String) {
        listener?.onReceivedTitle(view, title)
    }

    override fun onReceivedIcon(view: WebView, icon: Bitmap) {
        listener?.onReceivedIcon(view, icon)
    }

    override fun onReceivedTouchIconUrl(
        view: WebView,
        url: String,
        precomposed: Boolean
    ) {
        listener?.onReceivedTouchIconUrl(view, url, precomposed)
    }

    override fun onShowCustomView(view: View, callback: CustomViewCallback) {
        listener?.onShowCustomView(view, callback)
    }

    @Deprecated("")
    override fun onShowCustomView(
        view: View,
        requestedOrientation: Int,
        callback: CustomViewCallback
    ) {
        listener?.onShowCustomView(view, requestedOrientation, callback)
    }

    override fun onHideCustomView() {
        listener?.onHideCustomView()
    }

    override fun onCreateWindow(
        view: WebView,
        isDialog: Boolean,
        isUserGesture: Boolean,
        resultMsg: Message
    ): Boolean {
        return if (listener != null) {
            listener!!.onCreateWindow(view, isDialog, isUserGesture, resultMsg)
        } else {
            super.onCreateWindow(view, isDialog, isUserGesture, resultMsg)
        }
    }

    override fun onRequestFocus(view: WebView) {
        listener?.onRequestFocus(view)
    }

    override fun onCloseWindow(window: WebView) {
        listener?.onCloseWindow(window)
    }

    override fun onJsAlert(
        view: WebView,
        url: String,
        message: String,
        result: JsResult
    ): Boolean {
        return if (listener != null) {
            listener!!.onJsAlert(view, url, message, result)
        } else {
            super.onJsAlert(view, url, message, result)
        }
    }

    override fun onJsConfirm(
        view: WebView,
        url: String,
        message: String,
        result: JsResult
    ): Boolean {
        return if (listener != null) {
            listener!!.onJsConfirm(view, url, message, result)
        } else {
            super.onJsConfirm(view, url, message, result)
        }
    }

    override fun onJsPrompt(
        view: WebView,
        url: String,
        message: String,
        defaultValue: String,
        result: JsPromptResult
    ): Boolean {
        return if (listener != null) {
            listener!!.onJsPrompt(view, url, message, defaultValue, result)
        } else {
            super.onJsPrompt(view, url, message, defaultValue, result)
        }
    }

    override fun onJsBeforeUnload(
        view: WebView,
        url: String,
        message: String,
        result: JsResult
    ): Boolean {
        return if (listener != null) {
            listener!!.onJsBeforeUnload(view, url, message, result)
        } else {
            super.onJsBeforeUnload(view, url, message, result)
        }
    }

    override fun onGeolocationPermissionsShowPrompt(
        origin: String,
        callback: GeolocationPermissions.Callback
    ) {
        listener?.onGeolocationPermissionsShowPrompt(origin, callback)
    }

    override fun onGeolocationPermissionsHidePrompt() {
        listener?.onGeolocationPermissionsHidePrompt()
    }

    override fun onJsTimeout(): Boolean {
        return listener!!.onJsTimeout()

    }

    @Deprecated("")
    override fun onConsoleMessage(
        message: String,
        lineNumber: Int,
        sourceID: String
    ) {
        listener?.onConsoleMessage(message, lineNumber, sourceID)
    }

    override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
        return if (listener != null) {
            listener!!.onConsoleMessage(consoleMessage)
        } else {
            super.onConsoleMessage(consoleMessage)
        }
    }

    override fun getDefaultVideoPoster(): Bitmap? {
        return if (listener != null) {
            listener!!.defaultVideoPoster
        } else {
            super.getDefaultVideoPoster()
        }
    }

    override fun getVideoLoadingProgressView(): View? {
        return if (listener != null) {
            listener!!.videoLoadingProgressView
        } else {
            super.getVideoLoadingProgressView()
        }
    }

    override fun getVisitedHistory(callback: ValueCallback<Array<String>>?) {
        listener?.getVisitedHistory(callback)
    }

    @Deprecated("")
    override fun onExceededDatabaseQuota(
        url: String,
        databaseIdentifier: String,
        quota: Long,
        estimatedDatabaseSize: Long,
        totalQuota: Long,
        quotaUpdater: QuotaUpdater
    ) {
        listener?.onExceededDatabaseQuota(
            url,
            databaseIdentifier,
            quota,
            estimatedDatabaseSize,
            totalQuota,
            quotaUpdater
        )
    }

    @Deprecated("")
    fun onReachedMaxAppCacheSize(
        requiredStorage: Long,
        quota: Long,
        quotaUpdater: QuotaUpdater
    ) {
        if (listener != null) {
            listener!!.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater)
        } else {
            quotaUpdater.updateQuota(requiredStorage * 2)
        }
    }
}